package com.example.zhang;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.android.material.tabs.TabLayout;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.BreakIterator;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity implements Runnable {
    private static final String TAG = "RateActivity";
    float x,y1,y2,y3,y;
    float my=0.15f,yb=0.11f,hy=171.00f;
    String time = "123";
    String s;
    EditText input;
    TextView out;
    Handler handler;

    @SuppressLint("HandlerLeak")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        input = findViewById(R.id.you);
        out = findViewById(R.id.out);

        SharedPreferences sharedPreferences = getSharedPreferences("myrate", Activity.MODE_PRIVATE);
        PreferenceManager.getDefaultSharedPreferences(this);
        my = sharedPreferences.getFloat("my_save",0.0f);
        yb = sharedPreferences.getFloat("yb_save",0.0f);
        hy = sharedPreferences.getFloat("hy_save",0.0f);
        time = sharedPreferences.getString("time_save","123");

        Thread t = new Thread(this);//开启后会启动子线程中的run方法.
        t.start();

        handler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg){
                if(msg.what==7){
                    String str = (String)msg.obj;
                    out.setText(str);
                }
                super.handleMessage(msg);
            }
        };
    }




    private String inputStream2String(InputStream inputStream) throws IOException{                   //获取网页内容方法
        final int bufferSize =1024;
        final char[] buffer = new  char[bufferSize];
        final StringBuilder out = new StringBuilder();
        Reader in = new InputStreamReader(inputStream,"gb2312");
        while(true){
            int rsz = in.read(buffer,0,buffer.length);
            if(rsz<0)
                break;
            out.append(buffer,0,rsz);
        }
        return out.toString();
    }

    private void show() {
        out.setText(String.valueOf(y));
    }

    public void btn1(View v) {
        x=Float.parseFloat(input.getText().toString());
        y1=  my*x;
        y=y1;
        show();
    }
    public void btn2(View v){
        x=Float.parseFloat(input.getText().toString());
        y2= yb*x;
        y=y2;
        show();
    }
    public void btn3(View v){
        x=Float.parseFloat(input.getText().toString());
        y3= hy*x;
        y=y3;
        show();
    }
    public void btn4(View v){
        y=0;
        show();
    }
    public void openOne(View btn){
        open();

        //  startActivity(config);
    }

    private void open() {
        Intent config = new Intent(this, MainActivity_kiss.class);
        config.putExtra("my",my);
        config.putExtra("yb",yb);
        config.putExtra("hy",hy);
        startActivityForResult(config,5);

    }
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {



        if(requestCode==5 && resultCode==2){
            Bundle bundle = data.getExtras();
            my = bundle.getFloat("my_kiss",0.0f);
            yb = bundle.getFloat("yb_kiss",0.0f);
            hy = bundle.getFloat("hy_kiss",0.0f);


        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    public boolean onCreateOptionsMenu(Menu menu){
        getMenuInflater().inflate(R.menu.muen_first,menu);
        return true;
    }
    public boolean onOptionsItemSelected(MenuItem item){
        if(item.getItemId()==R.id.qwq){
            open();
        }
        return super.onOptionsItemSelected(item);
    }
    @Override
    public void run() {


        Log.i(TAG, "run....????");
        //https://www.usd-cny.com/

        URL url=null ;
        try{
            //url = new URL("http://www.usd-cny.com/bankofchina.htm");
            //HttpURLConnection http = (HttpURLConnection) url.openConnection();
            //InputStream in = http.getInputStream();
            //String html = inputStream2String(in);
            Date date = new Date();
            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
            Document doc = Jsoup.connect("http://www.usd-cny.com/bankofchina.htm").get();

            //Log.i(TAG,"run:title="+doc.title());
            //Element newsHeadlines = doc.getElementsByClass("time").first();
            //Log.i(TAG,"time"+newsHeadlines.text());

            if(time.equals(format.format(date)))
                Log.i(TAG, "今天已经更新过了！！！"+"程序更新时间是："+time );
           else {
                Elements pros = doc.getElementsByTag("tr");
               for(Element pro:pros) {
                   Elements data1 = pro.getElementsByTag("td");
                   if (data1.size() > 0) {

                       if (data1.get(0).text().equals("美元")) {
                           my = Float.parseFloat(data1.get(1).text());
                           Log.i(TAG, "name: " + data1.get(0).text() + " data：" + data1.get(1).text());
                       }
                       if (data1.get(0).text().equals("英镑")) {
                           yb = Float.parseFloat(data1.get(1).text());
                           Log.i(TAG, "name: " + data1.get(0).text() + " data：" + data1.get(1).text());
                       }
                       if (data1.get(0).text().equals("韩元")) {
                           hy = Float.parseFloat(data1.get(1).text());
                           Log.i(TAG, "name: " + data1.get(0).text() + " data：" + data1.get(1).text());
                       }
                   }

                   }
                SharedPreferences sp = getSharedPreferences("myrate",Activity.MODE_PRIVATE);
                SharedPreferences.Editor editor = sp.edit();
                editor.putFloat("my_save",my);
                editor.putFloat("yb_save",yb);
                editor.putFloat("hy_save",hy);
                editor.putString("time_save",format.format(date));
                editor.apply();
                Log.i(TAG, "完成每日更新"+time);

               }


        }
        catch (MalformedURLException e){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }


        try {                                                                                        //向页面传递信息
            Thread.sleep(3000);                                                               //延迟3S进行
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Message msg = handler.obtainMessage(7);
        msg.obj = "from message";
        handler.sendMessage(msg);



    }
    }
